// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections;
using System.Collections.Generic;

namespace SnapObjects.Data
{
    /// <summary>
    ///     Defines a template exporter where data can be exported from JSON or XML format to the specified template.
    /// </summary>
    public class TemplateExporter
    {
        /// <summary>
        ///     Exports data to the template.
        /// </summary>
        /// <param name="dataSource">The data to export.</param>
        /// <param name="template">The template for the data export.</param>
        /// <returns>Returns the data in the template.</returns>
        public static string Export(object dataSource, IDataTemplate template)
        {
            var engine = new DataTemplateEngine();

            var models = TemplateExporter.HandleDataSource(dataSource);

            var metadataProvider = ((DataTemplate)template).MetadataProvider;

            var templateProvider = new TemplateModelExportProvider(
                models, template.DataFormat, metadataProvider);

            return engine.Build(template, templateProvider);
        }

        private static IEnumerable<object> HandleDataSource(object dataSource)
        {
            if (!(dataSource is IEnumerable<object> models))
            {
                if (dataSource != null)
                {
                    var type = dataSource.GetType();

                    if (type.IsPrimitive || type == typeof(decimal) || type == typeof(string))
                    {
                        throw new NotSupportedException(
                            Properties.Resource.TEMPLATEEXPORT_NOTSUPPORT_DATASOURCE);
                    }

                    var listType = typeof(List<>).MakeGenericType(type);

                    models = (IEnumerable<object>)Activator.CreateInstance(listType);

                    ((IList)models).Add(dataSource);
                }
                else
                {
                    models = new List<object>();
                }
            }

            return models;
        }
    }
}
